package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 *
 * @author xiexiaoyu
 * @date 2025-01-15
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAlertDataService alertDataService;

    @Autowired
   private WebSocketServer webSocketServer;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    @Override
    public void alertFilter() {
        //定时任务过滤报警（每分钟触发一次）
        //查询有没有有效的规则
        long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        //若没有结束
        if(count==0){
            return;
        }
        //若有，则从redis中查询设备的最新数据
        List<Object> deviceDateLists = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_DATA_LASTEST);
        //若数据为空，则结束
        if(CollUtil.isEmpty(deviceDateLists)){
            return;
        }
        //若不为空，判断当前上报的数据是否超过了1分钟
        LocalDateTime now = LocalDateTime.now();
        deviceDateLists.forEach(deviceDatas -> {
            List<DeviceData> deviceDataList = (List<DeviceData>) deviceDatas;
            deviceDataList.forEach(deviceData -> {
                LocalDateTime alarmTime = deviceData.getAlarmTime();
                long between = ChronoUnit.SECONDS.between(now, alarmTime);
                //若超过则结束
                if(between>60){
                    return;
                }

                //若没超过，则遍历数据，交给数据报警处理器
                //调用方法将数据传递过去与报警规则进行匹配
                lertFilter(deviceData);
            });

        });

    }
    // 数据报警过滤器
    private void lertFilter(DeviceData deviceData) {

        //得到改产品下物模型下的规则（所有规则和对应规则）
        List<AlertRule> alertRules = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1)
                .in(AlertRule::getIotId,  -1,deviceData.getIotId())
        );
        //若规则为空，则结束，校验下一个数据
        if(CollUtil.isEmpty(alertRules)){
            return;
        }
        //若规则不为空，则遍历规则
        alertRules.forEach(alertRule -> {
            //定义REDIS中的持续周期
            String durationKey = "IOT:duration"+deviceData.getIotId()+":"+deviceData.getFunctionId()+":"+deviceData.getProductKey()+":"+alertRule.getId();
            //定义REDIS中的沉默周期
            String silenceKey = "IOT:silence"+deviceData.getIotId()+":"+deviceData.getFunctionId()+":"+deviceData.getProductKey()+":"+alertRule.getId();
            //四层校验
            //判断生效时间
            //若不在生效时间内，则结束
            String[] split = alertRule.getAlertEffectivePeriod().split("~");
            String start = split[0];
            LocalTime begin = LocalTime.parse(start);
            String end = split[1];
            LocalTime finish = LocalTime.parse(end);
            LocalDateTime alarmTime = deviceData.getAlarmTime();
            LocalTime time = alarmTime.toLocalTime();
            if(time.isBefore(begin)||time.isAfter(finish)){
                return;
            }
            //判断数据阈值
            Double value = alertRule.getValue();//阈值
            String operator = alertRule.getOperator();//运算符
            String dataValueStr = deviceData.getDataValue();
            Double dataValue = Double.valueOf(dataValueStr);//实际值
            if(">=".equals(operator)&&dataValue<value|| "<".equals(operator)&&dataValue>=value){
                redisTemplate.delete(durationKey);
                return;
            }
            //判断沉默周期
            Integer silence = (Integer) redisTemplate.opsForValue().get(silenceKey);
            if(silence!=null){
                return;
            }
            //判断持续周期
            Integer count = (Integer) redisTemplate.opsForValue().get(durationKey);
            if(ObjectUtil.isEmpty(count)){
                count=1;
            }else{
                count += 1;
            }
            Integer duration = alertRule.getDuration();
            if(!count.equals(duration)){
                redisTemplate.opsForValue().set(durationKey, count);
                return;
            }
            //若校验全部通过，则发送报警信息
            //删除redis中的报警数
            redisTemplate.delete(durationKey);
            //添加沉默周期到redis中
            redisTemplate.opsForValue().set(silenceKey, alertRule.getAlertSilentPeriod());
            //让报警数据保存到数据库中
            insertAlertData(deviceData, alertRule);
        });

    }
    //将报警数据保存到数据库中
    private void insertAlertData(DeviceData deviceData, AlertRule alertRule) {
        //判断是否是老人数据
        Integer physicalLocationType = deviceData.getPhysicalLocationType();
        List<Long> userIds;
        if(physicalLocationType==-1){
            //若是则判断是否是固定设备（睡眠监测带）
            Integer locationType = deviceData.getLocationType();
            if(locationType==1){
                //若是固定设备（睡眠监测带）则通过床位查询护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }else {
                //若不是（智能手表）则通过老人查护路员
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            }
        }else {
            //若不是。则是设备数据（烟雾传感器），则查询维修员
            userIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        //并查询超级管理员
        List<Long> managerIds = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");
        userIds.addAll(managerIds);
        //遍历获取到的用户id，将用户信息保存到集合中
        List<AlertData>  alertDataList = new ArrayList<>();
        userIds.forEach(userId -> {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
            alertData.setId(null);
            alertData.setAlertRuleId(alertRule.getId());
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
            alertData.setAlertReason(alertReason);
            alertData.setType(alertRule.getAlertDataType());
            alertData.setStatus(0);
            alertData.setUserId(userId);
            alertDataList.add(alertData);
        });
        //批量保存报警数据
        alertDataService.saveBatch(alertDataList);

           //将报警数据推送到websocket中
        sendMessageToConsumer(deviceData,alertRule,userIds);
    }

    private void sendMessageToConsumer(DeviceData data, AlertRule alertRule, List<Long> userIds) {
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(data, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        alertNotifyVo.setIsAllConsumer(false);
        webSocketServer.sendMessageToConsumer(alertNotifyVo, userIds);
    }

}
